// pages/main/workorder/process-record/process-record.js
Page({
  data: {
    records: [],
    filteredRecords: [],
    loading: true,
    searchKeyword: '',
    selectedStatus: '', // 选中的状态筛选
    statusOptions: [
      { label: '全部', value: '' },
      { label: '待处理', value: 'pending' },
      { label: '处理中', value: 'processing' },
      { label: '已完成', value: 'completed' },
      { label: '已取消', value: 'cancelled' }
    ],
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: true,
    loadingMore: false,
    error: false,
    errorMessage: ''
  },

  onLoad() {
    this.loadRecords();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      records: []
    });
    this.loadRecords(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMoreRecords();
    }
  },

  // 加载处理记录
  loadRecords(isRefresh = false) {
    if (!isRefresh) {
      this.setData({ loading: true });
    }
    
    const username = wx.getStorageSync('username') || '';
    
    wx.request({
      url: `${getApp().globalData.serverUrl}/GetWorkorderList/`,
      method: 'POST',
      data: {
        list_type: 'process', // 处理记录类型
        username: username,
        status: this.data.selectedStatus,
        page: 1,
        page_size: this.data.pageSize
      },
      success: (res) => {
        if (res.data.status) {
          const records = res.data.data || [];
          this.setData({
            records: records,
            filteredRecords: records,
            total: res.data.total || 0,
            page: 1,
            hasMore: records.length < (res.data.total || 0),
            loading: false,
            loadingMore: false,
            error: false,
            errorMessage: ''
          });
          
          // 应用搜索关键词过滤
          if (this.data.searchKeyword) {
            this.filterRecords();
          }
        } else {
          this.setData({
            loading: false,
            error: true,
            errorMessage: res.data.message || '获取处理记录失败'
          });
          wx.showToast({
            title: res.data.message || '获取处理记录失败',
            icon: 'none'
          });
        }
        
        if (isRefresh) {
          wx.stopPullDownRefresh();
        }
      },
      fail: (err) => {
        console.error('获取处理记录失败:', err);
        this.setData({
          loading: false,
          error: true,
          errorMessage: '网络错误，请稍后重试'
        });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        if (isRefresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 加载更多记录
  loadMoreRecords() {
    if (!this.data.hasMore || this.data.loadingMore) {
      return;
    }

    this.setData({ loadingMore: true });
    const username = wx.getStorageSync('username') || '';
    const nextPage = this.data.page + 1;

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetWorkorderList/`,
      method: 'POST',
      data: {
        list_type: 'process',
        username: username,
        status: this.data.selectedStatus,
        page: nextPage,
        page_size: this.data.pageSize
      },
      success: (res) => {
        if (res.data.status) {
          const newRecords = res.data.data || [];
          const allRecords = [...this.data.records, ...newRecords];
          
          this.setData({
            records: allRecords,
            filteredRecords: allRecords,
            page: nextPage,
            hasMore: allRecords.length < (res.data.total || 0),
            loadingMore: false
          });
          
          // 应用搜索关键词过滤
          if (this.data.searchKeyword) {
            this.filterRecords();
          }
        } else {
          this.setData({ loadingMore: false });
          wx.showToast({
            title: res.data.message || '加载更多失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('加载更多失败:', err);
        this.setData({ loadingMore: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 搜索输入变化
  onSearchChange(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterRecords();
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterRecords();
  },

  // 清除搜索
  onSearchClear() {
    this.setData({ 
      searchKeyword: '',
      filteredRecords: this.data.records
    });
  },

  // 取消搜索
  onSearchCancel() {
    this.setData({ 
      searchKeyword: '',
      filteredRecords: this.data.records
    });
  },

  // 过滤记录（根据搜索关键词）
  filterRecords() {
    const keyword = this.data.searchKeyword.toLowerCase().trim();
    if (!keyword) {
      this.setData({ filteredRecords: this.data.records });
      return;
    }

    const filtered = this.data.records.filter(record => {
      return (
        (record.workorder_number && record.workorder_number.toLowerCase().includes(keyword)) ||
        (record.type_name && record.type_name.includes(keyword)) ||
        (record.content && record.content.includes(keyword)) ||
        (record.location && record.location.includes(keyword)) ||
        (record.username && record.username.includes(keyword))
      );
    });

    this.setData({ filteredRecords: filtered });
  },

  // 状态筛选
  onStatusFilter(e) {
    const status = e.currentTarget.dataset.status || '';
    this.setData({ 
      selectedStatus: status,
      page: 1,
      hasMore: true
    });
    this.loadRecords();
  },

  // 点击工单项
  onRecordTap(e) {
    const record = e.currentTarget.dataset.record;
    // 跳转到详情页面
    wx.navigateTo({
      url: `/pages/main/workorder/workorder-detail/workorder-detail?id=${record.id}&source=process-record`
    });
  },

  // 重试加载
  onRetry() {
    this.setData({
      error: false,
      errorMessage: '',
      page: 1,
      hasMore: true
    });
    this.loadRecords();
  }
});
